/////////////////////////////////////////////////////////////////////////
//
// Amuse Engine SDK - core/threads
// Copyright (c) 2014.  All Rights Reserved
//
// File:		AESemaphore_win32.cpp
// Author:		Gianluca Belardelli
// Date:		13/03/2014
//
/////////////////////////////////////////////////////////////////////////
#ifndef WIN32
#error "Errore! Il file contiene codice specifico per Win32"
#endif

#include <AECore.h>

AESemaphore::AESemaphore( void )
{
	m_hSemaphore = NULL;
}

AESemaphore::AESemaphore( AEINT32 nValue, AEINT32 nMax )
{
	AEASSERT( nValue >= 0 && nMax > 0 && nValue <= nMax );
	m_hSemaphore = CreateSemaphore( NULL, nValue, nMax, NULL );
}

AESemaphore::~AESemaphore( void )
{
	CloseHandle( m_hSemaphore );
}
	
AEINT32 AESemaphore::Set( void )
{
	if( !ReleaseSemaphore( m_hSemaphore, 1, NULL ) )
		return AESemaphore_SetError;

	return AESemaphore_Ok;
}

AEINT32 AESemaphore::WaitInfinite( void )
{
	switch( WaitForSingleObject( m_hSemaphore, INFINITE ) )
	{
		case WAIT_OBJECT_0:
			return AESemaphore_Ok;
		default:
			return AESemaphore_WaitError;
	}
}

AEINT32 AESemaphore::Wait( AEINT32 uiMilliseconds )
{
	switch( WaitForSingleObject( m_hSemaphore, uiMilliseconds ) )
	{
		case WAIT_OBJECT_0:
			return AESemaphore_Ok;
		case WAIT_TIMEOUT:
			return AESemaphore_Timeout;
		default:
			return AESemaphore_WaitError;
	}
}
